import React, { useEffect, useState, useCallback, useMemo } from 'react';
import { Space, Table, Tag, Button, message, Input, Popconfirm, Typography, Tooltip, Modal, Upload } from 'antd';
import type { TableProps } from 'antd';
import { SearchOutlined, DeleteOutlined, UploadOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import http from '~/api/http';
import type { IPhysicalExam } from '~/types/examination';
import { EReportStatus } from '~/types/examination';

// 类型定义
type TableRowSelection<T extends object = object> = TableProps<T>['rowSelection'];
type PaginationConfig = { current: number; pageSize: number; };

const { Column } = Table;
const { confirm } = Modal;

// 常量定义
const PAGE_SIZE_OPTIONS = ['5', '10', '20', '50', '100'];
const DEFAULT_CURRENT_PAGE = 1;
const DEFAULT_PAGE_SIZE = 10;

// 报告状态配置
const REPORT_STATUS_CONFIG = {
  [EReportStatus.NOT_UPLOADED]: {
    text: '报告未上传',
    color: 'red'
  },
  [EReportStatus.UPLOADED]: {
    text: '报告已上传',
    color: 'green'
  },
  _: {
    text: '未知状态',
    color: 'default'
  }
};

const PhysicalExamUpload: React.FC = () => {
  // 表格选择相关状态
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [selectedExams, setSelectedExams] = useState<IPhysicalExam[]>([]);

  // 数据和加载状态
  const [loading, setLoading] = useState<boolean>(false);
  const [exams, setExams] = useState<Array<IPhysicalExam>>([]);
  const [totalCount, setTotalCount] = useState<number>(0);

  // 搜索和分页状态
  const [searchKeyword, setSearchKeyword] = useState<string>('');
  const [pagination, setPagination] = useState<PaginationConfig>({
    current: DEFAULT_CURRENT_PAGE,
    pageSize: DEFAULT_PAGE_SIZE,
  });

  // 文件上传状态
  const [uploading, setUploading] = useState<boolean>(false);
  const [uploadModalVisible, setUploadModalVisible] = useState<boolean>(false);
  const [currentExam, setCurrentExam] = useState<IPhysicalExam | null>(null);

  // 处理选择变化
  const handleSelectChange = useCallback((
    newSelectedRowKeys: React.Key[],
    selectedRows: IPhysicalExam[]
  ) => {
    setSelectedRowKeys(newSelectedRowKeys);
    setSelectedExams(selectedRows);
  }, []);

  // 行选择配置
  const rowSelection: TableRowSelection<IPhysicalExam> = useMemo(() => ({
    selectedRowKeys,
    onChange: handleSelectChange,
    selections: [
      Table.SELECTION_ALL,
      Table.SELECTION_INVERT,
      Table.SELECTION_NONE,
    ],
  }), [selectedRowKeys, handleSelectChange]);

  // 获取体检数据
  const fetchExams = useCallback(async (
    page: number = pagination.current,
    pageSize: number = pagination.pageSize,
    keyword?: string
  ) => {
    setLoading(true);
    try {
      const response = await http.getList<any>('TMemberExamination/page', {
        page,
        size: pageSize,
        fileNumber: keyword || searchKeyword,
        name: keyword || searchKeyword,
        phoneNumber: keyword || searchKeyword
      });

      // 处理返回数据，确保数据结构正确
      const processedData = response.data.map((item: any) => ({
        ...item,
        // 映射字段到正确的大小写
        TMember: item.tMember,
        TSetmeal: item.tSetmeal,
        // 确保有 MemberName 字段
        MemberName: item.tMember?.name,
        // 确保有 FileNumber 字段
        FileNumber: item.tMember?.fileNumber,
        // 确保有 PhoneNumber 字段
        PhoneNumber: item.tMember?.phoneNumber,
        // 确保有 SetName 字段
        SetName: item.tSetmeal?.name,
        // 映射其他字段
        ExamDate: item.examDate,
        ReportStatus: item.reportStatus,
      }));

      console.log('处理后的数据:', processedData); // 调试用
      setExams(processedData);
      setTotalCount(response.count);
    } catch (error) {
      console.error('获取体检数据失败:', error);
      message.error('获取体检数据失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  }, [pagination, searchKeyword]);

  // 初始化数据和依赖变化时重新获取
  useEffect(() => {
    fetchExams();
  }, [fetchExams]);

  // 处理搜索
  const handleSearch = useCallback(() => {
    setPagination(prev => ({ ...prev, current: DEFAULT_CURRENT_PAGE }));
    fetchExams(DEFAULT_CURRENT_PAGE, pagination.pageSize, searchKeyword);
  }, [fetchExams, pagination.pageSize, searchKeyword]);

  // 处理分页变化
  const handlePaginationChange = useCallback((page: number, pageSize: number) => {
    setPagination({ current: page, pageSize });
  }, []);

  // 删除单个体检记录
  const handleDeleteExam = useCallback(async (id: number, memberName: string) => {
    try {
      setLoading(true);
      await http.delete(`TMemberExamination/${id}`);
      message.success(`"${memberName}" 的体检记录删除成功！`);
      fetchExams();
    } catch (error) {
      console.error('删除体检记录失败:', error);
      message.error('删除体检记录失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  }, [fetchExams]);

  // 批量删除体检记录
  const handleBatchDelete = useCallback(() => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择要删除的体检记录');
      return;
    }

    confirm({
      title: '确认删除',
      icon: <ExclamationCircleOutlined />,
      content: `确定要删除选中的 ${selectedRowKeys.length} 条体检记录吗？此操作不可撤销。`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          setLoading(true);
          await http.deleteBatch(`TMemberExamination/batch`, selectedRowKeys);
          const memberNames = selectedExams.map(exam => exam.MemberName).join('、');
          message.success(`成功删除 ${memberNames} 等 ${selectedRowKeys.length} 条体检记录！`);
          setSelectedRowKeys([]);
          setSelectedExams([]);
          fetchExams();
        } catch (error) {
          console.error('批量删除体检记录失败:', error);
          message.error('批量删除体检记录失败，请稍后重试');
        } finally {
          setLoading(false);
        }
      },
    });
  }, [selectedRowKeys, selectedExams, fetchExams]);

  // 显示上传报告模态框
  const showUploadModal = (record: IPhysicalExam) => {
    setCurrentExam(record);
    setUploadModalVisible(true);
  };

  // 处理文件上传
  const handleUpload = useCallback(async (file: File) => {
    if (!currentExam) return false;

    setUploading(true);
    try {
      const formData = new FormData();
      formData.append('file', file);

      console.log('上传文件信息:', {
        体检记录ID: currentExam.id,
        会员姓名: currentExam.MemberName,
        文件名: file.name,
        文件大小: file.size,
        文件类型: file.type
      });

      // 1. 上传文件
      const uploadResponse = await http.post('File/upload/examination', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      });

      console.log('上传响应:', uploadResponse);

      if (uploadResponse.state === 200 && uploadResponse.code === "1") {
        // 2. 文件上传成功后，使用专门的接口更新报告状态
        try {
          // 使用正确的状态更新接口 - 注意：第二个参数是数字，不是对象
          const statusResponse = await http.put(`TMemberExamination/status/${currentExam.id}`, EReportStatus.UPLOADED);

          console.log('状态更新响应:', statusResponse);

          if (statusResponse.state === 200 && statusResponse.code === "1") {
            message.success(`"${currentExam.MemberName}" 的体检报告上传成功！`);
          } else {
            throw new Error(statusResponse.msg || '状态更新失败');
          }

          setUploadModalVisible(false);
          setCurrentExam(null);
          fetchExams();
        } catch (statusError) {
          console.error('更新报告状态失败:', statusError);
          // 即使状态更新失败，文件上传成功了，也提示成功
          message.success(`"${currentExam.MemberName}" 的报告文件上传成功，但状态更新失败`);
          setUploadModalVisible(false);
          setCurrentExam(null);
          fetchExams();
        }
      } else {
        throw new Error(uploadResponse.msg || `上传失败: ${uploadResponse.code}`);
      }
    } catch (error) {
      console.error('上传报告失败:', error);
      const errorMessage = error.response?.data?.msg ||
        error.message ||
        '上传报告失败，请稍后重试';
      message.error(errorMessage);
    } finally {
      setUploading(false);
    }

    return false;
  }, [currentExam, fetchExams]);

  // 自定义上传组件
  const uploadProps = {
    beforeUpload: (file: File) => {
      handleUpload(file);
      return false; // 阻止默认上传
    },
    showUploadList: false,
  };

  // 格式化日期
  const formatDate = (dateString?: string) => {
    if (!dateString) return '-';
    return dateString.split('T')[0];
  };

  // 获取报告状态显示
  const getReportStatus = (status?: number) => {
    const config = REPORT_STATUS_CONFIG[status as EReportStatus] || REPORT_STATUS_CONFIG._;
    return (
      <Tag color={config.color}>
        {config.text}
      </Tag>
    );
  };

  return (
    <div className="physical-exam-upload-container" style={{ padding: '20px' }}>
      <div style={{
        marginBottom: 16,
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center'
      }}>
        <Space size="middle">
          <Input
            placeholder="档案号/姓名/手机号"
            value={searchKeyword}
            onChange={(e) => setSearchKeyword(e.target.value)}
            style={{ width: 300 }}
            allowClear
            onPressEnter={handleSearch}
          />
          <Button type="primary" icon={<SearchOutlined />} onClick={handleSearch}>
            查询
          </Button>
        </Space>

        <Button
          danger
          icon={<DeleteOutlined />}
          disabled={selectedRowKeys.length === 0}
          onClick={handleBatchDelete}
        >
          批量删除
        </Button>
      </div>

      <div style={{ marginBottom: 16 }}>
        <Typography.Text>
          共搜索到 {totalCount} 条数据
        </Typography.Text>
      </div>

      <Table<IPhysicalExam>
        loading={loading}
        dataSource={exams}
        rowKey="id"
        rowSelection={rowSelection}
        pagination={{
          total: totalCount,
          current: pagination.current,
          pageSize: pagination.pageSize,
          showTotal: (total) => `共 ${total} 条`,
          showSizeChanger: true,
          showQuickJumper: true,
          pageSizeOptions: PAGE_SIZE_OPTIONS,
          position: ['bottomCenter'],
          onChange: handlePaginationChange
        }}
        scroll={{ x: 'max-content' }}
      >
        <Column
          title="体检时间"
          dataIndex="ExamDate"
          key="ExamDate"
          width={120}
          render={(date) => formatDate(date)}
        />
        <Column
          title="档案号"
          dataIndex="FileNumber"
          key="fileNumber"
          width={120}
          render={(fileNumber) => fileNumber || '-'}
        />
        <Column
          title="姓名"
          dataIndex="MemberName"
          key="name"
          width={100}
          render={(name) => name || '-'}
        />
        <Column
          title="手机号码"
          dataIndex="PhoneNumber"
          key="phoneNumber"
          width={130}
          ellipsis={{ showTitle: false }}
          render={(phone) => (
            <Tooltip title={phone} placement="top">
              {phone || '-'}
            </Tooltip>
          )}
        />
        <Column
          title="检测套餐"
          dataIndex="SetName"
          key="setmealName"
          width={150}
          render={(setName) => setName || '一般体检项'}
        />
        <Column
          title="报告状态"
          dataIndex="ReportStatus"
          key="ReportStatus"
          width={120}
          render={getReportStatus}
        />
        <Column
          title="操作"
          key="action"
          width={180}
          render={(_: any, record: IPhysicalExam) => (
            <Space size="middle">
              <Button
                type="primary"
                size="small"
                icon={<UploadOutlined />}
                onClick={() => showUploadModal(record)}
                disabled={record.ReportStatus === EReportStatus.UPLOADED}
              >
                上传报告
              </Button>
              <Popconfirm
                title={`确定要删除 "${record.MemberName}" 的体检记录吗？`}
                onConfirm={() => handleDeleteExam(record.id, record.MemberName || '')}
                okText="确定"
                cancelText="取消"
              >
                <Button danger icon={<DeleteOutlined />} size="small">
                  删除
                </Button>
              </Popconfirm>
            </Space>
          )}
        />
      </Table>

      {/* 上传报告模态框 */}
      <Modal
        title="上传体检报告"
        open={uploadModalVisible}
        onCancel={() => {
          setUploadModalVisible(false);
          setCurrentExam(null);
        }}
        footer={null}
        width={400}
      >
        {currentExam && (
          <div style={{ padding: '20px 0' }}>
            <div style={{ marginBottom: 16 }}>
              <Typography.Text strong>会员信息：</Typography.Text>
              <div style={{ marginTop: 8 }}>
                <div>姓名：{currentExam.MemberName}</div>
                <div>档案号：{currentExam.FileNumber}</div>
                <div>手机号：{currentExam.PhoneNumber}</div>
                <div>体检套餐：{currentExam.SetName || '一般体检项'}</div>
              </div>
            </div>

            <Upload {...uploadProps}>
              <Button
                icon={<UploadOutlined />}
                loading={uploading}
                type="primary"
                block
              >
                {uploading ? '上传中...' : '选择报告文件'}
              </Button>
            </Upload>

            <div style={{ marginTop: 8, fontSize: 12, color: '#999' }}>
              支持格式：PDF、JPG、PNG，文件大小不超过10MB
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default PhysicalExamUpload;